This page has been superceded by a wiki version of this example: SwitchCaseExample

The switch-case Construct

Let's say you write a program that has a menu with a bunch of mutually exclusive options.


+---------+------+-------+------+

| File    | Edit | Tools | Help |

+---------+------+-------+------+

| New     |

| Open    |

| Save    |

| Print   |

|---------+

| Exit    |

+---------+

This is just the kind of situation that lead to the creation of the switch-case construct: only one of these options can be clicked at any given time. You can't click "Open" and "Exit" at the same time. So let's just go down the list. Maybe "New" was clicked, so run subroutine NewWasClicked(). If "Open" was clicked, then run subroutine OpenWasClicked(). And so on down list. If "Exit" was clicked then just PostQuitMessage(0). Finally the default case is there so that you can catch whatever might fall through the cracks.

D follows in the C/C++ tradition of "falling through" from the matched case to the cases below if there isn't a break statement. So unless you actually want all the code for the lower cases executed when the upper case is found, don't forget to include those breaks.

D


int main()

{

    int i;



    switch(i)

    {

        case 0: 

            printf("i is zero"); 

            break;  

            /* Without each "break", 

               the flow will fall-through. */



        case 1: 

            printf("i is one");  

            break;



        case 2:

            printf("i is one");  

            break;

    

        default: 

            printf("i is one");  

            break;

    }

    return 0;

}
QuickBASIC
Dim i%



Select Case i%

    Case 0: Print "i is zero" 

    Case 1: Print "i is one" 

    Case 2: Print "i is two" 

    Case 3: Print "i is three" 

    Case Else: Print "i is something else"

End Select
Output i is zero

Compiling this example

Compile this program simply by sending it to the D compiler at the commandline:

dmd switch-case.html
(DMD must be in your path for this to work.)

Automatic Initialization

When the integer i is declared, it is automatically assigned a default value of 0.


Return to Tutorial Overview